package com.example.chat.task;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.example.chat.domain.entity.Friendship;
import com.example.chat.domain.entity.GroupInvite;
import com.example.chat.domain.entity.Moment;
import com.example.chat.service.FriendshipService;
import com.example.chat.service.GroupInviteService;
import com.example.chat.service.MomentService;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

@Component
@Slf4j
public class FriendVerifyTask {

    @Resource
    private FriendshipService friendshipService;
    @Resource
    private GroupInviteService groupInviteService;
    @Resource
    private MomentService momentService;

    private ExecutorService service;

    @PostConstruct
    public void init() {
        this.service = Executors.newFixedThreadPool(3);
    }

    @PreDestroy
    public void destroy() {
        service.shutdown();
    }

    @Scheduled(cron = "0 0 0/1 * * ?")
    public void verifyTimeOut_updateStatus(){
        service.execute(() -> {
            try {
//                log.info("开始处理过期好友验证状态...");
                List<Friendship> friendList = friendshipService.lambdaQuery()
                        .in(Friendship::getStatus, List.of(0, 2))
                        .le(Friendship::getCreateTime, LocalDateTime.now().minusHours(12))
                        .list();
                List<Long> friendIds = friendList.stream().map(Friendship::getId).collect(Collectors.toList());
                if (friendIds != null && !friendIds.isEmpty()) {
                    friendshipService.lambdaUpdate()
                            .in(Friendship::getId, friendIds)
                            .set(Friendship::getStatus, 3)
                            .update();
                }
//                log.info("开始处理过期群邀请状态...");
                List<GroupInvite> groupList = groupInviteService.lambdaQuery()
                        .in(GroupInvite::getStatus, List.of(0, 2))
                        .le(GroupInvite::getCreateTime, LocalDateTime.now().minusHours(12))
                        .list();
                List<Long> groupIds = groupList.stream().map(GroupInvite::getId).collect(Collectors.toList());
                if (groupIds != null && !groupIds.isEmpty()) {
                    groupInviteService.lambdaUpdate()
                            .in(GroupInvite::getId, groupIds)
                            .set(GroupInvite::getStatus, 3)
                            .update();
                }
                log.info("更新完成：更新的好友记录ID列表: {}共{}条好友验证状态，" +
                        "更新的群邀请记录ID列表: {}共{}条群邀请状态",friendIds,friendIds.size(),groupIds,groupIds.size());
            } catch (Exception e) {
                log.error("处理过期状态任务异常");
            }
        });

    }

    @Scheduled(cron = "0 0 0/2 * * ?")
    public void verifyTimeOut_deleteRecord(){
        service.execute(()->{
//            log.info("开始删除过期好友记录...");
            List<Friendship> list = friendshipService.lambdaQuery()
                    .eq(Friendship::getStatus, 3)
                    .le(Friendship::getCreateTime, LocalDateTime.now().minusHours(24))
                    .list();
            List<Long> ids = list.stream().map(Friendship::getId).collect(Collectors.toList());
            if(ids != null && ids.size() > 0){
                friendshipService.removeBatchByIds(ids);
            }
//            log.info("开始删除过期或确认的群邀请记录...");
            List<GroupInvite> list1 = groupInviteService.lambdaQuery()
                    .in(GroupInvite::getStatus, List.of(1, 3))
                    .le(GroupInvite::getCreateTime, LocalDateTime.now().minusHours(24))
                    .list();
            List<Long> ids2 = list1.stream().map(GroupInvite::getId).collect(Collectors.toList());
            if(ids2 != null && ids2.size() > 0){
                groupInviteService.removeBatchByIds(ids2);
            }

//            log.info("开始删除动态...");
            List<Moment> list3 = momentService.lambdaQuery()
                    .eq(Moment::getVisibility, 0)
                    .list();
            List<Long> ids3 = list3.stream().map(Moment::getId).collect(Collectors.toList());
            if(ids3 != null && ids3.size() > 0){
                momentService.removeBatchByIds(ids3);
            }
            log.info("删除完成：删除的好友记录id列表:{}共{}条好友记录," +
                    "删除的群邀请记录id列表:{}共{}条群邀请," +
                    "删除的动态记录id列表{}共{}条动态",ids,ids.size(),ids2,ids2.size(),ids3,ids3.size());
        });
    }

}
